package com.example.teachingSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teachingSystem.mapper.EnrollmentMapper;
import com.example.teachingSystem.mapper.PermissionMapper;
import com.example.teachingSystem.pojo.entity.Enrollment;
import com.example.teachingSystem.pojo.entity.Permission;
import com.example.teachingSystem.pojo.form.course.AddEnrollmentForm;
import com.example.teachingSystem.service.EnrollmentService;
import com.example.teachingSystem.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 86147
 * @description 针对表【enrollment(选课表)】的数据库操作Service实现
 * @createDate 2023-11-27 21:43:54
 */
@Service
public class EnrollmentServiceImpl extends ServiceImpl<EnrollmentMapper, Enrollment>
        implements EnrollmentService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Result<String> addEnrollment(AddEnrollmentForm addEnrollmentForm, Boolean isAdmin) {
        if (!isAdmin) {
            if (!permissionMapper.exists(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getCode, "SELECT").eq(Permission::getStatus, true))) {
                return Result.build(null, 500, "选课系统未开放");
            }
        }
        List<Enrollment> enrollments = new ArrayList<>();
        addEnrollmentForm.getCourseIds().forEach(item -> {
            Enrollment one = new Enrollment();
            one.setStudentId(addEnrollmentForm.getStudentId());
            one.setCourseId(item);
            enrollments.add(one);
        });
        this.saveBatch(enrollments);
        return Result.ok(null, "选课成功");
    }

    @Override
    public Result<String> deleteEnrollment(List<Long> ids, Boolean isAdmin) {
        if (!isAdmin) {
            if (!permissionMapper.exists(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getCode, "SELECT").eq(Permission::getStatus, true))) {
                return Result.build(null, 500, "选课系统未开放");
            }
        }
        this.removeBatchByIds(ids);
        return Result.ok(null, "退课成功");
    }
}




